package com.small.xx.ai.spring.vector.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.elasticsearch.ElasticsearchVectorStore;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ConditionalOnProperty(prefix = "spring.ai.vectorstore.elasticsearch", name = "enabled", havingValue = "true")
@RestController
@RequestMapping("chat/vector/es")
public class EsVectorController {

    private static final Logger logger = LoggerFactory.getLogger(EsVectorController.class);
    private final ElasticsearchVectorStore elasticsearchVectorStore;

    @Autowired
    public EsVectorController(
        @Qualifier("elasticsearchVectorStore") ElasticsearchVectorStore elasticsearchVectorStore) {
        this.elasticsearchVectorStore = elasticsearchVectorStore;
    }

    @GetMapping("/add")
    public void add() {
        logger.info("start import data");

        HashMap<String, Object> map = new HashMap<>();
        map.put("year", 2025);
        map.put("name", "XX");
        List<Document> documents = List.of(new Document("世界很大， 救赎就潜伏在角落。"),
            new Document("你面向过去前行，又转身面向未来。", Map.of("year", 2024)),
            new Document("Spring AI太棒了！Spring AI太棒了！Spring AI太棒了！Spring AI太棒了！Spring AI太棒了！", map),
            new Document("其他", "测试内容", map));
        elasticsearchVectorStore.add(documents);
    }

    @GetMapping("/search")
    public List<Document> search() {
        logger.info("start search data");
        return elasticsearchVectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(2).build());
    }

    @GetMapping("delete-filter")
    public void deleteFilter() {
        logger.info("start delete data with filter");
        FilterExpressionBuilder b = new FilterExpressionBuilder();
        Filter.Expression expression = b.and(b.in("year", 2025, 2024), b.eq("name", "XX")).build();

        elasticsearchVectorStore.delete(expression);
    }
}
